import magic
from pathlib import Path

class AudioFormatDetector:
    AUDIO_MAGIC_HEADERS = {
        b'ID3': 'mp3',
        b'OggS': 'ogg',
        b'fLaC': 'flac',
        b'RIFF': 'wav',
        b'wvpk': 'wv',
        b'DSD ': 'dsf',
        b'mp4a': 'm4a',
        b'\x52\x61\x72\x21\x1A\x07\x00': 'ape',
        b'\x00\x00\x00\x18ftypM4A ': 'alac',
        b'\x00\x00\x00\x1CftypM4A ': 'mqa'
    }

    def __init__(self):
        self.mime = magic.Magic(mime=True)
        
    def detect(self, file_path: Path) -> str:
        if not file_path.exists():
            raise FileNotFoundError(f"File {file_path} not found")
            
        # 快速魔数检测
        with file_path.open('rb') as f:
            header = f.read(12)
            
        for magic_bytes, fmt in self.AUDIO_MAGIC_HEADERS.items():
            if header.startswith(magic_bytes):
                return fmt
                
        # 回退到全文件扫描
        mime_type = self.mime.from_file(str(file_path))
        if mime_type.startswith('audio/'):
            return mime_type[6:].lower()
            
        return 'unknown'